package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.pop.PopListImageDir;
import com.github.postsanf.yinian.adapter.LocalManagePuzzleAdapter;
import com.github.postsanf.yinian.bean.YNFileComparator;
import com.github.postsanf.yinian.bean.YNFileInfo;
import com.github.postsanf.yinian.bean.YNImageFloder;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.utils.Crop;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

/**
 * 发布相册管理页面
 */
public class LocalPuzzleManageActivity extends BaseActivity implements PopListImageDir.OnImageDirSelected, View.OnClickListener, ISkinUpdate {
    private Toolbar mToolbar;
    private LinearLayout ll_album_title_btn;
    private TextView tv_album_name_show;                // 相册名
    private LocalManagePuzzleAdapter mAdapter;                        // 相册适配器
    private PopListImageDir mListImageDirPopupWindow;        // 弹窗相册路径
    private GridView mGirdView;                        // 网格布局
    private ProgressDialog mProgressDialog;                // 进度条
    private int mScreenHeight;                    // 屏高
    private int mPicsSize;                        // 文件夹图片数量
    private File mImgDir;                        // 图片数量最多的文件夹
    private List<String> mImgs = new ArrayList<>();                            // 所有的图片
    private List<String> mfristImgsnew = new ArrayList<>();
    private ImageView iv_btn_expend_switch;
    private RelativeLayout rl_album_manage_bottom;
    private RelativeLayout rl_pop_top;
    private TextView mPreview;                        // 预览
    private TextView mUpLoad;                            // 上传
    private TextView mComplete;                            // 已完成张数
    private HashSet<String> mDirPaths = new HashSet<String>();
    private List<YNImageFloder> mImageFloders = new ArrayList<YNImageFloder>();
    private List<YNImageFloder> mImageFlodersnew = new ArrayList<YNImageFloder>();
    private Resources mResource;
    private File mTempDir;
    private String imagelocal;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (mProgressDialog != null)
                mProgressDialog.dismiss();
            // 为View绑定数据
            data2View();
            // 初始化展示文件夹的popupWindw
            initListDirPopupWindw();
        }
    };
    private Handler numHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    showToast("只能选择"
                            + UIHelper.MIN_IMG_COUNT
                            + getString(R.string.photo_select_tip_end));
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        setContentView(R.layout.yn_activity_day_sign);
        mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
        if (!(mTempDir.mkdir() || mTempDir.isDirectory())) {
            mTempDir.mkdirs();
        }
        BaseApplication.getInstance().mActivitys.add(this);
        mScreenHeight = DisplayUtils.getScreenHeightPixels(this);
        initView();
        getImages();
        initEvent();
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.local_manage_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);

        mUpLoad = (TextView) findViewById(R.id.btn_album_manage_sure);
        mComplete = (TextView) findViewById(R.id.btn_album_manage_complete);

        mGirdView = (GridView) findViewById(R.id.gv_album_gridView);
        mPreview = (TextView) findViewById(R.id.btn_album_manage_preview);
        tv_album_name_show = (TextView) findViewById(R.id.tv_album_name_show);
        ll_album_title_btn = (LinearLayout) findViewById(R.id.ll_album_title_btn);
        rl_pop_top = (RelativeLayout) findViewById(R.id.rl_pop_top);
        iv_btn_expend_switch = (ImageView) findViewById(R.id.iv_btn_expend_switch);
        rl_album_manage_bottom = (RelativeLayout) findViewById(R.id.rl_album_manage_bottom);

        mUpLoad.setOnClickListener(this);
        mPreview.setOnClickListener(this);
    }

    // 数据绑定
    private void data2View() {
        if (mImgDir == null) {
            showToast("图片没扫描到");
            return;
        }
//        Log.d("yuhao", "mImageFloders.size()=" + mImageFloders.size());
        for (int j = 0; j < mImageFloders.size(); j++) {
            mImgDir = new File(mImageFloders.get(j).getDir());
            File[] files = mImgDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    String filename = file.getName().toLowerCase();
                    if (file.length() > 0 && !filename.contains(".9")) {
                        if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                || filename.endsWith(".jpeg"))
                            return true;
                    }
                    return false;
                }
            });
            if (files != null) {
                for (int k = 0; k < files.length; k++) {
                    mfristImgsnew.add(files[k].getAbsolutePath());
                }
            }
        }
        ArrayList<YNFileInfo> fileList = new ArrayList<>();
        for (int i = 0; i < mfristImgsnew.size(); i++) {
            File file = new File(mfristImgsnew.get(i));
            double imgLat = 0.0, imgLong = 0.0;
            float[] arr = new float[2];
            try {
                imgLat = arr[0];
                imgLong = arr[1];
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (file.length() > 0) {
                YNFileInfo fileInfo = new YNFileInfo();
                fileInfo.setName(file.getName());
                fileInfo.setPath(file.getAbsolutePath());
                fileInfo.setLatitude(imgLat);
                fileInfo.setLongitude(imgLong);
                fileInfo.setLastModified(file.lastModified());
                fileList.add(fileInfo);
            }
        }
        Collections.sort(fileList, new YNFileComparator());
        mImgs.clear();
        for (int j = 0; j < fileList.size(); j++) {
            mImgs.add(fileList.get(j).getPath());
        }
        mAdapter = new LocalManagePuzzleAdapter(getApplicationContext(), mImgs, R.layout.yn_album_grid_item, this, numHandler);
        if (mResource != null) {
            mAdapter.setResource(mResource);
        }
        mGirdView.setAdapter(mAdapter);
    }

    private String switchSure(int val) {
        return val == 0 ? "" : "(" + val + ")";
    }

    // 初始化展示文件夹的popupWindw
    private void initListDirPopupWindw() {
        YNImageFloder imageFloder = new YNImageFloder();
        imageFloder.setDir("所有图片");
        imageFloder.setCount(mImgs.size());
        if (mImgs.size() > 0) {
            imageFloder.setFirstImagePath(mImgs.get(0));
            mImageFlodersnew.add(imageFloder);
        }
        mImageFlodersnew.addAll(mImageFloders);
        mListImageDirPopupWindow = new PopListImageDir(
                ViewGroup.LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
                mImageFlodersnew, LayoutInflater.from(getApplicationContext())
                .inflate(R.layout.yn_album_list_dir, null));
        mListImageDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                iv_btn_expend_switch.setImageResource(R.drawable.btn_expend);
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        // 设置选择文件夹的回调
        mListImageDirPopupWindow.setOnImageDirSelected(this);
    }

    /**
     * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描，最终获得jpg最多的那个文件夹
     */
    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            showToast("暂无外部存储");
            return;
        }
        // 显示进度条
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_DATA);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                ContentResolver mContentResolver = LocalPuzzleManageActivity.this
                        .getContentResolver();
                // 只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    // 拿到第一张图片的路径
                    if (firstImage == null)
                        firstImage = path;
                    // 获取该图片的父路径名
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    YNImageFloder imageFloder = null;
                    // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        // 初始化imageFloder
                        imageFloder = new YNImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }
                    File[] pics = new File(dirPath).listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".png")
                                    || filename.toLowerCase().endsWith(".jpeg"))
                                return true;
                            return false;
                        }
                    });
                    int picSize = (pics != null) ? pics.length : 0;
                    imageFloder.setCount(picSize);
                    mImageFloders.add(imageFloder);
                    if (picSize > mPicsSize) {
                        mPicsSize = picSize;
                        mImgDir = parentFile;
                    }
                }
                mCursor.close();
                // 扫描完成，辅助的HashSet也就可以释放内存了
                mDirPaths = null;
                // 通知Handler扫描图片完成
                mHandler.sendEmptyMessage(0x110);
            }
        }).start();
    }

    private void initEvent() {
        // 相册列表触发
        ll_album_title_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_btn_expend_switch.setImageResource(R.drawable.btn_expend_up);
                mListImageDirPopupWindow.showAsDropDown(rl_pop_top, 0, 0);
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = .9f;
                getWindow().setAttributes(lp);
            }
        });
    }

    @Override
    public void selected(YNImageFloder floder) {
        ArrayList<YNFileInfo> fileList = new ArrayList<>();
        File[] files = null;
        if (floder.getDir().equals("所有图片")) {
            files = new File[mfristImgsnew.size()];
            for (int i = 0; i < mfristImgsnew.size(); i++) {
                files[i] = new File(mfristImgsnew.get(i));
            }
        } else {
            mImgDir = new File(floder.getDir());
            files = mImgDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    String filename = file.getName().toLowerCase();
                    if (file.length() > 0 && !filename.contains(".9")) {
                        if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                || filename.endsWith(".jpeg"))
                            return true;
                    }
                    return false;
                }
            });
        }
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String imgPath = file.getAbsolutePath();
//            String imgTime = "", refLat = "", refLong = "";
            double imgLat = 0.0, imgLong = 0.0;
            boolean flag = true;
            float[] arr = new float[2];
            try {
                //android读取图片EXIF信息
                ExifInterface exifInterface = new ExifInterface(imgPath);
                flag = exifInterface.getLatLong(arr);
                imgLat = arr[0];
                imgLong = arr[1];
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (file.length() > 0) {
                YNFileInfo fileInfo = new YNFileInfo();
                fileInfo.setName(file.getName());
                fileInfo.setPath(file.getAbsolutePath());
                fileInfo.setLatitude(imgLat);
                fileInfo.setLongitude(imgLong);
                fileInfo.setLastModified(file.lastModified());
                fileList.add(fileInfo);
            }
        }
        Collections.sort(fileList, new YNFileComparator());
        mImgs.clear();
        for (int j = 0; j < fileList.size(); j++) {
            mImgs.add(fileList.get(j).getPath());
        }
        //  可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
        mAdapter = new LocalManagePuzzleAdapter(getApplicationContext(), mImgs,
                R.layout.yn_album_grid_item, this, numHandler);
        mGirdView.setAdapter(mAdapter);
        tv_album_name_show.setText(floder.getName());
        mListImageDirPopupWindow.dismiss();
    }

    public void setSureCount(int totals) {
        //mComplete.setText(totals == 0 ? "" : totals + "/8");
        mUpLoad.setText("上传" + switchSure(totals));
        mPreview.setText("预览" + switchSure(totals));
    }


    // 开始剪切过程
    private void beginCrop(Uri source) {
        String fileName = "Temp_" + String.valueOf(System.currentTimeMillis()) + ".png";
        File cropFile = new File(mTempDir, fileName);
        Uri outputUri = Uri.fromFile(cropFile);
        new Crop(source).output(outputUri).asX359Y359().setCropType(false).start(this);
    }

    // 处理图像剪切结果
    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            SelectedImg.mSelectedImage.clear();
            try {
                imagelocal = ImageUtils.getImageAbsolutePath19(this, Crop.getOutput(result));
            } catch (Exception e) {
                e.printStackTrace();
            }
            startActivity(new Intent(LocalPuzzleManageActivity.this, PuzzleMakeActivity.class).putExtra("imagelocal", imagelocal));
            finish();
        } else if (resultCode == Crop.RESULT_ERROR) {
            showToast("处理图片失败");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_album_manage_sure:
                if (SelectedImg.mSelectedImage.size() <= 0) {
                    showToast("请选择相片后再上传");
                    return;
                }
                beginCrop(Uri.parse("file:///" + SelectedImg.mSelectedImage.get(0)));
                break;
            case R.id.btn_album_manage_preview:
                if (SelectedImg.mSelectedImage.size() <= 0) {
                    showToast("请选择相片后再预览");
                    return;
                }
                Intent toPreview = new Intent(this, PreviewActivity.class);
                startActivity(toPreview);
                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_FROM_CAMERA:
                if (resultCode == RESULT_CANCELED) {
                    ImageUtils.deleteImageUri(this, ImageUtils.imageUriFromCamera);
                } else {
                    Uri imageUriCamera = ImageUtils.imageUriFromCamera;
                    String camerUrl = ImageUtils.getImageAbsolutePath19(this, imageUriCamera);
                    Uri Uri = android.net.Uri.parse("file:///" + camerUrl);
                    beginCrop(Uri);
                }
                break;
            case Crop.REQUEST_CROP:
                handleCrop(resultCode, data);
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        AnimateFirstDisplayListener.displayedImages.clear();
        sendBroadcast(new Intent(ACTIONs.updataMcardEdit));
        super.onBackPressed();
        // SelectedImg.mSelectedImage.clear();
    }

    /**
     * 图片加载监听事件
     **/
    public static class AnimateFirstDisplayListener extends
            SimpleImageLoadingListener {
        public static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    displayedImages.add(imageUri); // 将图片uri添加到集合中
                }
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setSureCount(SelectedImg.mSelectedImage.size());
        mAdapter.notifyDataSetChanged();
    }

    // 清除选中并退出
    private void clearAll() {
        SelectedImg.mSelectedImage.clear();
        finish();
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseAlbum:
                    int noClear = intent.getExtras().getInt(ACTIONs.aIsClearSelect);
                    if (1 == noClear) {
                        finish();
                    } else {
                        clearAll();
                    }
                    break;
                case ACTIONs.actionUpdateUpNum:
                    setSureCount(SelectedImg.mSelectedImage.size());
                    break;
            }
        }
    };

    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        myIntentFilter.addAction(ACTIONs.actionUpdateUpNum);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        BaseApplication.getInstance().mActivitys.remove(this);
        AnimateFirstDisplayListener.displayedImages.clear();
        SelectedImg.mSelectedImage.clear();
        this.unregisterReceiver(mBroadcastReceiver);
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_cancel, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
//            case R.id.action_cancel:
//                // 发消息取消上传
//                new AlertDialog.Builder(LocalDaysignManageActivity.this).setMessage("确定取消？")
//                        .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int whichButton) {
////                                Intent mIntent = new Intent(ACTIONs.actionCloseAlbum);
////                                mIntent.putExtra(ACTIONs.aIsClearSelect, 0);
////                                sendBroadcast(mIntent);
//                            }
//                        }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                }).show();
//                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void updateTheme() {
        if (mToolbar != null) {
            try {
                mResource = SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                tv_album_name_show.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                rl_album_manage_bottom.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                mUpLoad.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                mPreview.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
